package com.bbs.controller;

import com.bbs.domain.ResultInfo;
import com.bbs.entity.User;
import com.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Objects;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 去注册和登录的页面
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @ResponseBody
    @PostMapping("/register")
    public ResultInfo register(@RequestBody User user) {
        ResultInfo resultInfo = new ResultInfo();
        // 判断两次密码相同
        if (!Objects.equals(user.getPassword(), user.getRepassword())) {
            resultInfo.setCode("1");
            resultInfo.setMsg("注册失败，两次密码不相同");
            return resultInfo;
        }
        int flag = userService.register(user);

        if (flag == 1) {
            resultInfo.setCode("0");
            resultInfo.setMsg("注册成功，请激活后登录");
        } else if (flag == 2) {
            resultInfo.setCode("1");
            resultInfo.setMsg("该用户已经注册");
        } else {
            resultInfo.setCode("1");
            resultInfo.setMsg("注册失败，请重新注册");
        }
        return resultInfo;
    }


    /**
     * 登录
     *
     * @param userParam 用户信息
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultInfo doLogin(@RequestBody User userParam, HttpSession session) {
        String email = userParam.getEmail();
        String password = userParam.getPassword();
        session.setAttribute("email",email);
        session.setAttribute("password",password);
        User user = userService.loginSelectUser(userParam.getEmail());
        session.setAttribute("uid",user.getId());
        //调用service 方法校验邮箱和密码
        return userService.doLogin(email, password, session);

    }

    @GetMapping("/activatUser")
    @ResponseBody
    public ResultInfo activatUser(String email, String activateCode) {
        User user = userService.activatUser(email, activateCode);
        ResultInfo resultInfo = new ResultInfo();
        if (user == null) {
            resultInfo.setCode("1");
            resultInfo.setMsg("邮箱或激活码不正确!!");
            return resultInfo;
        }

        resultInfo.setCode("0");
        resultInfo.setMsg("激活成功");
        return resultInfo;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            session.removeAttribute(attributeNames.nextElement());
        }
        return "index";
    }
}
